package webDevelopment.tcp;


import webDevelopment.util.Log;

import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.HashMap;
import java.util.Scanner;

public class TranslateServerShortConnection {
    public static final int PORT = 8888;

    public static void main(String[] args) throws Exception {
        Log.println("启动短连接版本的 TCP 服务器");
        initMap();
        ServerSocket serverSocket = new ServerSocket(PORT);
        while (true) {
            // 接电话
            Log.println("等待对方来连接");
            Socket socket = serverSocket.accept();
            Log.println("有客户端连接上来了");

            // 对方信息：
            InetAddress inetAddress = socket.getInetAddress();  // ip
            Log.println("对方的 ip: " + inetAddress);
            int port = socket.getPort();    // port
            Log.println("对方的 port: " + port);
            SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress();    // ip + port
            Log.println("对方的 ip + port: " + remoteSocketAddress);

            // 读取请求
            InputStream inputStream = socket.getInputStream();
            Scanner scanner = new Scanner(inputStream, "UTF-8");
            String request = scanner.nextLine();    // nextLine() 就会去掉换行符
            String engWord = request;
            Log.println("英文: " + engWord);

            // 翻译
            String chiWord = translate(engWord);
            Log.println("中文: " + chiWord);

            // 发送响应
            String response = chiWord;  // TODO: 响应的单词中是没有 \r\n

            OutputStream outputStream = socket.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, "UTF-8");
            PrintWriter writer = new PrintWriter(outputStreamWriter);

            Log.println("准备发送");
            writer.printf("%s\r\n", response);

            writer.flush();
            Log.println("发送成功");

            // 挂掉电话
            socket.close();
            Log.println("挂断电话");
        }
//        serverSocket.close();
    }


    private static final HashMap<String, String> map = new HashMap<>();

    private static void initMap() {
        map.put("apple", "苹果");
        map.put("pear", "梨");
        map.put("orange", "橙子");
    }

    private static String translate(String engWord) {
        String chiWord = map.getOrDefault(engWord, "查无此单词");
        return chiWord;
    }
}
